<?php

namespace app\api\controller;


use app\admin\model\GoodsCollect;
use app\common\controller\Api;

/**
 * 我的收藏
 */
class Collect extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];


    /**
     * 商品收藏列表显示
     *
     */
    public function index()
    {
        $model = new GoodsCollect();
        $data = $model->where(['status' => 1])
            ->with('goods')
            ->field('goods_collect.id,goods_id,score,old_score,image')
            ->select();
        foreach ($data as &$v) {
            $v['image'] = config("url_domain_root") . $v->goods->image;
            $v['goods_title'] = $v->goods->title;
            unset($v->goods);
        }
        $this->success('获取成功！', $data, 1);
    }

    /**
     * 商品收藏列表详情
     *
     */
    public function addCollect()
    {
        $model = new GoodsCollect();
        $goods_id = input('post.goods_id/d');
        if (empty($goods_id)) {
            $this->error('请选择商品', [], 500);
        }
        $res = $model->where(['user_id' => 1, 'goods_id' => $goods_id])->find();
        if (!empty($res)) {
            if ($model->where('id', $res->id)->delete()) {
                $this->success('取消收藏成功', [], 1);
            }
        } else {
            $res['user_id'] = 1;
            $res['goods_id'] = $goods_id;
            if ($model->save($res)) {
                $this->success('添加成功', [], 1);
            }
            $this->error('添加失败', [], 500);
        }
    }

    /*
     * 取消收藏
     * */
    public function deleteCollect()
    {
        $id = input('get.id/a', 0);
        $model = new GoodsCollect();
        if (count($id) <= 0) {
            $this->error('请选择取消收藏的商品', [], 0);
        }
        foreach ($id as $k => $v) {
            $data = $model->find($v);
            if (empty($data)) {
                unset($id[$k]);
            }
            $model::destroy($v);
        }
        $this->success('取消成功', [], 1);
    }
}
